package com.trump.baiduim.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import lombok.*;
import org.springframework.context.annotation.Configuration;

import java.io.Serializable;
import java.text.SimpleDateFormat;

/**
 * 后续看项目周期实现自定义注解进行处理进行解耦
 *
 * @author guoyuans
 */
@Configuration
@Data
public class ResultUtil<T> implements Serializable {
    /**
     * 是否成功
     */
    private Boolean success;
    /**
     * 获取当前时间
     */
    String times = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(System.currentTimeMillis());
    /**
     * 状态码
     */
    private Integer code;
    /**
     * 错误描述
     */
    private String msg;
    /**
     * token
     */
    private String token;
    /**
     * 数据内容
     */
    private T data;

    /**
     * 不带数据内容成功返回
     * @return
     */
    public ResultUtil ofSuccess() {
        return ofSuccess(null);
    }

    /**
     * 带数据内容成功返回
     *
     * @param data 数据内容
     * @return
     */
    public ResultUtil ofSuccess(Object data) {
        ResultUtil result = new ResultUtil();
        result.code = 200;
        result.success = true;
        result.msg = "";
        result.setData(data);
        return result;
    }

    /**
     * 不带数据内容错误返回
     *
     * @param code 自定义error code
     * @param msg  自定义错误描述
     * @return
     */
    public ResultUtil ofFail(Integer code, String msg) {
        ResultUtil result = new ResultUtil();
        result.success = false;
        result.code = code;
        result.msg = msg;
        return result;
    }

    /**
     * 带数据内容返回
     *
     * @param code 自定义error code
     * @param msg  自定义错误描述
     * @param data 数据内容
     * @return
     */
    public ResultUtil ofFail(Integer code, String msg, Object data) {
        ResultUtil result = new ResultUtil();
        result.success = false;
        result.code = code;
        result.msg = msg;
        result.setData(data);
        return result;
    }

    /**
     * 从枚举类获取error code，返回错误结果
     *
     * @param errorEnum error code枚举类
     * @return
     */
    public ResultUtil ofFail(ErrorCode errorEnum) {
        ResultUtil result = new ResultUtil();
        result.success = false;
        result.code = errorEnum.getCode();
        result.msg = errorEnum.getMessage();
        return result;
    }

    /**
     * 返回结果封装成json
     *
     * @return json报文
     */
    public String buildResultJson() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("success", this.success);
        jsonObject.put("code", this.code);
        jsonObject.put("times", this.times);
        jsonObject.put("msg", this.msg);
        jsonObject.put("token", this.token);
        jsonObject.put("data", this.data);
        return JSON.toJSONString(jsonObject, SerializerFeature.DisableCircularReferenceDetect);
    }
}
